package cn.bb.dao;

import cn.bb.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.stereotype.Component;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
@Component("userTemp")
public class UserTemplateDao implements IUserDao {
    public static final RowMapper rowMapper = new ParameterizedRowMapper() {
        @Override
        public User mapRow(ResultSet rs, int i) throws SQLException {
            User u = new User();
            u.setId(rs.getInt("id"));
            u.setPwd(rs.getString("pwd"));
            return u;
        }
    };
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Override
    public List<User> search() {
        String sql ="select * from t_user";

        List<User> userList=jdbcTemplate.query(sql,rowMapper);
        return userList;
    }

    @Override
    public List<User> search(User user) {
        return null;
    }

    @Override
    public User getById(int id) {
        String sql ="select * from t_user where id=?";
        Object[] parames = {id};
        List<User> list =jdbcTemplate.query(sql,rowMapper,parames);
        return list.size()>0?list.get(0):null;
    }

    @Override
    public int addUser(User user) {
        //字段能不能是 name 关键字  否则会报错
        String sql = "insert into t_user(pwd) values(?)";
        Object[] parames = {user.getPwd()};
        return jdbcTemplate.update(sql,parames);

    }

    @Override
    public int updateUser(User user) {
        return 0;

    }

    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
}
